<?php

/**
 * 分销核心MODEL文件 - AM
 * 版本：V2.0
 */

if (!defined('IN_IA')) {
    die( 'Access Denied' );
}
define('TM_COMMISSION_AGENT_NEW', 'commission_agent_new');
define('TM_COMMISSION_ORDER_PAY', 'commission_order_pay');
define('TM_COMMISSION_ORDER_FINISH', 'commission_order_finish');
define('TM_COMMISSION_APPLY', 'commission_apply');
define('TM_COMMISSION_CHECK', 'commission_check');
define('TM_COMMISSION_PAY', 'commission_pay');
define('TM_COMMISSION_UPGRADE', 'commission_upgrade');
define('TM_COMMISSION_BECOME', 'commission_become');
if (!class_exists('CommissionModel')) {
    class CommissionModel extends PluginModel {

        public function getSet(){
            $set = parent::getSet();

            $set['texts'] = array(
                'agent' => empty( $set['texts']['agent'] ) ? '分销商' : $set['texts']['agent'],
                'shop' => empty( $set['texts']['shop'] ) ? '小店' : $set['texts']['shop'],
                'myshop' => empty( $set['texts']['myshop'] ) ? '我的小店' : $set['texts']['myshop'],
                'center' => empty( $set['texts']['center'] ) ? '分销中心' : $set['texts']['center'],
                'become' => empty( $set['texts']['become'] ) ? '成为分销商' : $set['texts']['become'],
                'withdraw' => empty( $set['texts']['withdraw'] ) ? '提现' : $set['texts']['withdraw'],
                'commission' => empty( $set['texts']['commission'] ) ? '佣金' : $set['texts']['commission'],
                'commission1' => empty( $set['texts']['commission1'] ) ? '分销佣金' : $set['texts']['commission1'],
                'commission_total' => empty( $set['texts']['commission_total'] ) ? '累计佣金' : $set['texts']['commission_total'],
                'commission_ok' => empty( $set['texts']['commission_ok'] ) ? '可提现佣金' : $set['texts']['commission_ok'],
                'commission_apply' => empty( $set['texts']['commission_apply'] ) ? '已申请佣金' : $set['texts']['commission_apply'],
                'commission_check' => empty( $set['texts']['commission_check'] ) ? '待打款佣金' : $set['texts']['commission_check'],
                'commission_lock' => empty( $set['texts']['commission_lock'] ) ? '未结算佣金' : $set['texts']['commission_lock'],
                'commission_detail' => empty( $set['texts']['commission_detail'] ) ? '佣金明细' : $set['texts']['commission_detail'],
                'order' => empty( $set['texts']['order'] ) ? '分销订单' : $set['texts']['order'],
                'myteam' => empty( $set['texts']['myteam'] ) ? '我的团队' : $set['texts']['myteam'],
                'myteam1' => empty( $set['texts']['myteam1'] ) ? '一级下线' : $set['texts']['myteam1'],
                'myteam2' => empty( $set['texts']['myteam2'] ) ? '二级下线' : $set['texts']['myteam2'],
                'myteam3' => empty( $set['texts']['myteam3'] ) ? '三级下线' : $set['texts']['myteam3'],
                'special' => empty( $set['texts']['special'] ) ? '环保特使' : $set['texts']['special'],
                'orderprice' => empty( $set['texts']['orderprice'] ) ? '分销订单额' : $set['texts']['orderprice'],
            );

            return $set;
        }

        /**
         * 获取计算结果
         * @param int $orderid
         * @param bool $save
         * @return array|bool
         */
        public function getCalculate($orderid = 0, $save = false){
            global $_W;

            $set = $this->getSet();

            if (empty( $orderid ) || $set['level'] <= 0) {
                return false;
            }

            $defalutLevel = array( 'levelname' => '默认等级', 'commission1' => $set['commission1'], 'commission2' => $set['commission2'], 'commission3' => $set['commission3'], );

            // 获取订单涉及的用户信息，修改此处获取规则，理论支持无限级。
            $agents = $this->getAgents($orderid);

            // 获取所有分销商等级
            $levels = $this->getLevels();

            $result = array();

            if (!empty( $agents )) {

                $i = 1;
                foreach ($agents as $key => $agent) {
                    $agents[$key]['c_rank'] = $i;       // 分佣级别
                    $i++;

                    if (!empty( $levels )) {
                        foreach ($levels as $level) {
                            if ($agent['agentlevel'] == $level['id']) {
                                $agents[$key]['agentlevel'] = $level;
                                break;
                            }
                        }
                    }

                    // 若分销商等级被删除时，is_array 判断将会使用户的佣金比例为默认。
                    if (empty( $agent['agentlevel'] ) || !is_array($agents[$key]['agentlevel'])) {
                        $agents[$key]['agentlevel'] = $defalutLevel;
                    }
                }

                // 获取订单详细信息
                $order = m('order')->getOrderInfo($orderid);
                $goods = m('order')->getGoodsByOrderId($orderid);

                if (!empty( $order ) && !empty( $goods )) {
                    foreach ($agents as $key => $agent) {
                        foreach ($goods as $good) {
                            $tempResult['uniacid'] = $_W['uniacid'];
                            $tempResult['mid'] = $agent['id'];
                            $tempResult['orderid'] = $orderid;
                            $tempResult['o_create_time'] = $order['createtime'];
                            $tempResult['o_pay_time'] = $order['paytime'];
                            $tempResult['o_finish_time'] = $order['finishtime'];
                            $tempResult['o_status'] = $order['status'];
                            $tempResult['c_rank'] = $agent['c_rank'];
                            $tempResult['goods_id'] = $good['goodsid'];
                            $tempResult['cg_money'] = $good['realprice'];  // 默认佣金为支付的实际金额
                            $tempResult['c_type'] = 0;

                            $price = $good['realprice'];

                            // 商品启用独立分销
                            if ($good['hascommission'] == 1) {

                                $keyRate = 'commission' . $agent['c_rank'] . '_rate';   // 按比例分佣，优先
                                $keyPay = 'commission' . $agent['c_rank'] . '_pay';     // 按固定金额分佣

                                if (!empty( $good[$keyRate] ) && $good[$keyRate] > 0) {
                                    $tempResult['c_rate'] = $good[$keyRate];
                                    $c_rate = $good[$keyRate];
                                    $tempResult['c_money'] = round($c_rate * $price / 100, 2);
                                } else {
                                    $tempResult['c_rate'] = 0;      // 固定金额分佣时，分销比例为0
                                    $tempResult['c_type'] = 1;
                                    $tempResult['c_money'] = round($good[$keyPay] * $good['total'], 2);
                                }
                            } else {
                                $keyRate = 'commission' . $agent['c_rank'];
                                $tempResult['c_rate'] = $agent['agentlevel'][$keyRate];
                                $c_rate = $agent['agentlevel'][$keyRate];

                                $tempResult['c_money'] = round($c_rate * $price / 100, 2);
                            }

                            $result[] = $tempResult;

                            unset( $tempResult );
                        }
                    }
                }

            }

            unset( $order, $goods, $agents, $levels, $set );

            if (!empty( $save ) && !empty( $result )) {
                $this->saveCalculate(0, $result);
            }

            return $result;
        }

        /**
         * 更新佣金记录
         * @param int $orderid
         * @param array $params
         * @return bool
         */
        public function saveCalculate($orderid = 0, $params = array()){

            if (!empty( $orderid ) || !empty( $params )) {

                if (empty( $params )) {
                    $params = $this->getCalculate($orderid);
                }

                if (!$this->_checkCalculateParams($params)) {
                    return false;
                }

                if (!empty( $params )) {
                    foreach ($params as $param) {
                        $status = pdo_insert('ewei_shop_commission_record', $param);

                        if (empty( $status )) {
                            message('更新佣金记录出错。');
                        }
                    }

                    return true;
                }
            }

            return false;
        }

        /**
         * 佣金记录更新前的数据检测。
         * @param array $params
         * @return bool
         */
        private function _checkCalculateParams($params = array()){

            if (!empty( $params )) {

                $result = true;

                $sql = 'SELECT count(id) FROM ' . tablename('ewei_shop_commission_record') . ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `orderid` = :orderid AND `goods_id` = :goods_id ';

                foreach ($params as $param) {
                    if (empty( $param['uniacid'] ) || empty( $param['mid'] ) || empty( $param['orderid'] ) || empty( $param['goods_id'] ) || empty( $param['cg_money'] )) {
                        $result = false;
                        break;
                    }

                    // 已经存在订单，且用户ID，商品ID一致时，都不允许更新。
                    $logCount = pdo_fetchcolumn($sql, array( ':uniacid' => $param['uniacid'], ':mid' => $param['mid'], ':orderid' => $param['orderid'], ':goods_id' => $param['goods_id'] ));

                    if ($logCount >= 1) {
                        $result = false;
                        break;
                    }
                }

                return $result;
            }

            return false;
        }

        /**
         * 更新commission_record的订单状态
         * @param $orderid
         * @param $type
         * @return bool
         */
        private function _updateRecordOrderStatus($orderid, $type){
            global $_W;

            if (!empty( $orderid ) && !empty( $type )) {
                $time = time();

                switch ($type) {
                    case 'pay' :
                        $data = array( 'o_status' => 1, 'o_pay_time' => $time );
                        break;
                    case 'send' :
                        $data = array( 'o_status' => 2, 'o_send_time' => $time );
                        break;
                    case 'finish' :
                        $data = array( 'o_status' => 3, 'o_finish_time' => $time );
                        break;
                    default :
                        $data = array();
                        break;
                }

                if (!empty( $data )) {
                    if (is_array($orderid)) {
                        foreach ($orderid as $value) {
                            pdo_update('ewei_shop_commission_record', $data, array( 'uniacid' => $_W['uniacid'], 'orderid' => $value ));
                        }
                    } else {
                        pdo_update('ewei_shop_commission_record', $data, array( 'uniacid' => $_W['uniacid'], 'orderid' => $orderid ));
                    }
                    return true;
                }
            }

            return false;
        }


        /**
         * 获取指定用户所属的佣金记录， 默认获取指定用户所有状态的记录。
         * $orderStatus || $commissionStatus
         * 可以填写数组，例: array(1,2,3), 即获取对应状态订单。
         * 也可填写指定数值，获取指定状态订单。
         * @param $openid // 可填写openid 或 mid
         * @param array $orderStatus 订单状态。-1删除，0确认，1支付，2发货，3完成
         * @param array $commissionStatus 佣金状态。-2删除，-1无效，0未申请，1申请，2审核通过 3已打款
         * @param int $offset 偏移值
         * @param int $limit 结果数
         * @param bool $time 记录时间
         * @return array
         */
        public function getCommissionRecord($openid, $orderStatus = array(), $commissionStatus = array(), $offset = 0, $limit = 20, $time = false){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            if ($time) {
                $recordSql = ' SELECT `id`, `orderid`, `goods_id`, `o_create_time`, `o_pay_time`, `o_finish_time`, `o_status`, ';
                $recordSql .= ' `c_type`, `c_rank`, `c_rate`, `c_money`, `c_apply_time`, `c_check_time`, `c_pay_time`, `c_invalid_time`, `c_status` ';
            } else {
                $recordSql = ' SELECT `id`, `orderid`, `goods_id`, `o_status`, `c_type`, `c_rank`, `c_rate`, `c_money`, `c_status` ';
            }

            $recordSql .= ' FROM ' . tablename('ewei_shop_commission_record');
            $recordSql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid ';

            $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

            // 订单状态
            if (is_array($orderStatus)) {
                $recordSql .= ' AND `o_status` IN ( ' . implode(',', $orderStatus) . ' ) AND `c_status` >= 0 ';
            } else {
                if (!empty( $orderStatus ) || $orderStatus == 0) {
                    $recordSql .= ' AND `o_status` = :o_status AND `c_status` >= 0 ';
                    $params[':o_status'] = intval($orderStatus);
                }
            }

            // 佣金状态
            if (is_array($commissionStatus) && !empty($commissionStatus)) {
                $recordSql .= ' AND `o_status` IN ( ' . implode(',', $orderStatus) . ' )';
            } else {
                if (!empty( $commissionStatus ) || $commissionStatus == 0) {
                    $recordSql .= ' AND `c_status` = :c_status ';
                    $params[':c_status'] = intval($commissionStatus);
                }
            }

            $recordSql .= ' ORDER BY `o_create_time` DESC ';

            if ($offset >= 0 && !empty( $limit )) {
                $recordSql .= ' LIMIT ' . $offset . ' , ' . $limit;
                $result = pdo_fetchall($recordSql, $params);
            } else {

                // 仅在不存在limit时进行缓存。避免过多的limit缓存，剥夺I/O资源。
                $key = $_W['uniacid'] . '_commission_record_' . $mid . '_' . md5($recordSql);
                $result = WsCache::getCache($key);

                if (empty( $result )) {
                    $result = pdo_fetchall($recordSql, $params);
                    WsCache::setCache($key, $result);
                }
            }

            return $result;
        }

        /**
         * 获取指定用户的指定状态的佣金。
         * @param $openid // 可填写openid 或 mid
         * @param array $options // 获取佣金金额选项 ( TOTAL = 总额， OK = 可提现， LOCK = 不可提现， APPLY = 正在申请， PAY = 已支付 )
         * @return array
         */
        public function getCommissionRecordPrice($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $set = $this->getSet();

            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;

            $result = array();

            if (in_array('total', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` >= 3 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );
                $sum = pdo_fetchcolumn($sql, $params);
                $result['total'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('ok', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` < :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['ok'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('lock', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` > :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['lock'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['apply'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['check'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['pay'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            if (in_array('invalid', $options)) {
                $sql = ' SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $sum = pdo_fetchcolumn($sql, $params);
                $result['invalid'] = !empty( $sum ) ? number_format($sum, 2) : 0;
            }

            return $result;
        }

        /**
         * 获取指定用户，指定状态的佣金记录。
         * @param $openid // 可填写openid 或 mid
         * @param array $options // 获取佣金金额选项 ( TOTAL = 总额， OK = 可提现， LOCK = 不可提现， APPLY = 正在申请， PAY = 已支付 )
         * @return array
         */
        public function getCommissionRecordLists($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $set = $this->getSet();

            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;

            $result = array();

            if (in_array('total', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` > 1 ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['total'] = pdo_fetchall($sql, $params);
            }

            if (in_array('ok', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` <= :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['ok'] = pdo_fetchall($sql, $params);
            }

            if (in_array('lock', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` > :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['lock'] = pdo_fetchall($sql, $params);
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['apply'] = pdo_fetchall($sql, $params);
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['check'] = pdo_fetchall($sql, $params);
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['pay'] = pdo_fetchall($sql, $params);
            }

            if (in_array('invalid', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['invalid'] = pdo_fetchall($sql, $params);
            }

            return $result;
        }

        /**
         * 获取指定状态的统计信息。
         * @param $openid // 可填写openid 或 mid
         * @param array $options // 获取佣金金额选项
         * ( TOTAL = 总额， OK = 可提现， LOCK = 不可提现， APPLY = 正在申请， PAY = 已支付 )
         * ( o_status_0 - o_status_3 分别代表订单下单 -> 完成)
         * @return array
         */
        public function getCommissionRecordStatistics($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $set = $this->getSet();

            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;

            $result = array();

            if (in_array('total', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` > 3 AND `c_status` >= 0 ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['total'] = pdo_fetch($sql, $params);
            }

            if (in_array('ok', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` <= :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['ok'] = pdo_fetch($sql, $params);
            }

            if (in_array('lock', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 0 AND `o_finish_time` > :o_finish_time ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':o_finish_time' => $time - $day_times );

                $result['lock'] = pdo_fetch($sql, $params);
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['apply'] = pdo_fetch($sql, $params);
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['check'] = pdo_fetch($sql, $params);
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['pay'] = pdo_fetch($sql, $params);
            }

            if (in_array('invalid', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['invalid'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_0', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 0 AND `c_status` >= 0 ';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_0'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_1', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 1 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_1'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_2', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 2 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_2'] = pdo_fetch($sql, $params);
            }

            if (in_array('o_status_3', $options)) {
                $sql = ' SELECT SUM(cg_money) AS cg_money_sum, COUNT(DISTINCT orderid) AS order_count, SUM(c_money) AS c_money_sum FROM ' . tablename('ewei_shop_commission_record');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = 3 AND `c_status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['o_status_3'] = pdo_fetch($sql, $params);
            }

            return $result;
        }

        /**
         * 获取团队信息
         * @param $openid
         * @param int $level
         * @param int $offset
         * @param int $limit
         * @return array
         */
        public function getCommissionTeam($openid, $level = 3, $offset = 0, $limit = 20, $refreshCache = false){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $levelAgents_1 = $levelAgents_2 = $levelAgents_3 = array();
            $result = array();

            $key = $_W['uniacid'] . '_commission_team_' . $mid;
            $agents = WsCache::getCache($key);

            $set = $this->getSet();

            // 强制刷新缓存
            if($refreshCache == true){
                $agents = array();
            }

            // 无缓存时，获取所有信息后，进行缓存。
            if (empty( $agents )) {

                if ($set['level'] >= 1) {
                    $sql = 'SELECT * FROM ' . tablename('ewei_shop_member') . ' WHERE agentid = :agentid AND isagent = 1 AND status = 1 AND uniacid = :uniacid ';
                    $levelAgents_1 = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'], ':agentid' => $mid ), 'id');

                    $agents['levelAgents_1'] = $levelAgents_1;
                }

                if ($set['level'] >= 2 && !empty( $levelAgents_1 )) {
                    $sql = 'SELECT * FROM ' . tablename('ewei_shop_member') . ' WHERE agentid IN( ' . implode(',', array_keys($levelAgents_1)) . ') AND isagent = 1 AND status = 1 AND uniacid = :uniacid';
                    $levelAgents_2 = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ), 'id');

                    $agents['levelAgents_2'] = $levelAgents_2;
                }

                if ($set['level'] >= 3 && !empty( $levelAgents_2 )) {
                    $sql = 'SELECT * FROM ' . tablename('ewei_shop_member') . ' WHERE agentid IN( ' . implode(',', array_keys($levelAgents_2)) . ') AND isagent = 1 AND status = 1 AND uniacid = :uniacid';
                    $levelAgents_3 = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ), 'id');

                    $agents['levelAgents_3'] = $levelAgents_3;
                }

                WsCache::setCache($key, $agents);
            }

            //$offset = intval($offset - 1) <= 0 ? 0 : intval($offset - 1);

            if ($level == 1 && $set['level'] >= 1 && !empty( $agents['levelAgents_1'] )) {
                return array_slice($agents['levelAgents_1'], $offset, $limit);
            }

            if ($level == 2 && $set['level'] >= 2 && !empty( $agents['levelAgents_2'] )) {
                return array_slice($agents['levelAgents_2'], $offset, $limit);
            }

            if ($level == 3 && $set['level'] >= 3 && !empty( $agents['levelAgents_3'] )) {
                return array_slice($agents['levelAgents_3'], $offset, $limit);
            }

            return false;
        }

        /**
         * 获取团队信息
         * @param $openid
         * @param int $level
         * @param int $offset
         * @param int $limit
         * @return array
         */
        public function getCommissionTeamAll($openid, $level = 3, $offset = 0, $limit = 20, $refreshCache = false){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $levelAgents_1 = $levelAgents_2 = $levelAgents_3 = array();
            $result = array();

            $key = $_W['uniacid'] . '_commission_team_all_' . $mid;
            $agents = WsCache::getCache($key);

            $set = $this->getSet();

            // 强制刷新缓存
            if($refreshCache == true){
                $agents = array();
            }

            // 无缓存时，获取所有信息后，进行缓存。
            if (empty( $agents )) {

                if ($set['level'] >= 1) {
                    $sql = 'SELECT * FROM ' . tablename('ewei_shop_member') . ' WHERE agentid = :agentid AND status = 1 AND uniacid = :uniacid ';
                    $levelAgents_1 = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'], ':agentid' => $mid ), 'id');

                    $agents['levelAgents_1'] = $levelAgents_1;
                }

                if ($set['level'] >= 2 && !empty( $levelAgents_1 )) {
                    $sql = 'SELECT * FROM ' . tablename('ewei_shop_member') . ' WHERE agentid IN( ' . implode(',', array_keys($levelAgents_1)) . ') AND status = 1 AND uniacid = :uniacid';
                    $levelAgents_2 = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ), 'id');

                    $agents['levelAgents_2'] = $levelAgents_2;
                }

                if ($set['level'] >= 3 && !empty( $levelAgents_2 )) {
                    $sql = 'SELECT * FROM ' . tablename('ewei_shop_member') . ' WHERE agentid IN( ' . implode(',', array_keys($levelAgents_2)) . ') AND status = 1 AND uniacid = :uniacid';
                    $levelAgents_3 = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ), 'id');

                    $agents['levelAgents_3'] = $levelAgents_3;
                }

                WsCache::setCache($key, $agents);
            }

            $offset = intval($offset - 1) <= 0 ? 0 : intval($offset - 1);

            if ($level == 1 && $set['level'] >= 1 && !empty( $agents['levelAgents_1'] )) {
                return array_slice($agents['levelAgents_1'], $offset, $limit);
            }

            if ($level == 2 && $set['level'] >= 2 && !empty( $agents['levelAgents_2'] )) {
                return array_slice($agents['levelAgents_2'], $offset, $limit);
            }

            if ($level == 3 && $set['level'] >= 3 && !empty( $agents['levelAgents_3'] )) {
                return array_slice($agents['levelAgents_3'], $offset, $limit);
            }

            return false;
        }

        /**
         * 获取团队数量
         * @param $openid
         * @param array $level
         * @param bool $all
         * @return array
         */
        public function getCommissionTeamCount($openid, $level = array( 1, 2, 3 ), $all = false){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $result = array();

            if (!empty( $level )) {
                $levels = array();

                if (!is_array($level)) {
                    for ($i = 1; $i <= $level; $i++) {
                        $levels[] = $i;
                    }
                } else {
                    $levels = $level;
                }

                $teamAll = 0;

                foreach ($levels as $v) {
                    if($all){
                        $tempTeam = $this->getCommissionTeamAll($mid, $v, 0, null);
                    }else{
                        $tempTeam = $this->getCommissionTeam($mid, $v, 0, null);
                    }


                    $result[$v] = $count = !empty( $tempTeam ) ? count($tempTeam) : 0;

                    $teamAll += $count;
                }

                $result['all'] = $teamAll;
            }

            return $result;
        }

        /**
         * 某一用户发起提现申请
         * @param $openid
         * @param $type
         * @return bool|int
         */
        public function getWithdrawals($openid, $type){
            global $_W;

            $commissionLists = $this->getCommissionRecordLists($openid, array( 'ok' ));

            $commissionListsOk = $commissionLists['ok'];
            $commissionPriceOk = 0;

            if (!empty( $commissionListsOk )) {
                $orderids = array();

                $mid = intval($openid);

                if (empty( $mid )) {
                    $mid = m('member')->getMid($openid);
                }

                foreach ($commissionListsOk as $list) {
                    if (!in_array($list['orderid'], $orderids)) {
                        $orderids[] = $list['orderid'];
                    }

                    $commissionPriceOk += $list['c_money'];
                }

                $result = $this->_updateCommissionStatus($mid, $orderids, 'apply');

                if (!empty( $result )) {

                    $applyno = m('common')->createNO('commission_apply', 'applyno', 'CA');

                    $apply = array( 'uniacid' => $_W['uniacid'], 'applyno' => $applyno, 'orderids' => iserializer($orderids), 'mid' => $mid, 'commission' => $commissionPriceOk, 'type' => intval($type), 'status' => 1, 'applytime' => time() );

                    pdo_insert('ewei_shop_commission_apply', $apply);

                    return $commissionPriceOk;
                }

            }

            return false;
        }

        /**
         * 更新commission_record的佣金状态
         * @param $orderid
         * @param $type
         * @return bool
         */
        private function _updateCommissionStatus($openid, $orderid, $type){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            if (!empty( $orderid ) && !empty( $type )) {
                $time = time();

                switch ($type) {
                    case 'apply' :
                        $data = array( 'c_status' => 1, 'c_apply_time' => $time );
                        break;
                    case 'check' :
                        $data = array( 'c_status' => 2, 'c_check_time' => $time );
                        break;
                    case 'pay' :
                        $data = array( 'c_status' => 3, 'c_pay_time' => $time );
                        break;
                    default :
                        $data = array();
                        break;
                }

                if (!empty( $data )) {
                    if (is_array($orderid)) {
                        foreach ($orderid as $value) {
                            pdo_update('ewei_shop_commission_record', $data, array( 'uniacid' => $_W['uniacid'], 'orderid' => $value, 'mid' => $mid ));
                        }
                    } else {
                        pdo_update('ewei_shop_commission_record', $data, array( 'uniacid' => $_W['uniacid'], 'orderid' => $orderid, 'mid' => $mid ));
                    }

                    return true;
                }
            }

            return false;
        }

        /**
         * 提现记录统计
         * @param $openid
         * @param array $options
         * @param int $offset
         * @param int $limit
         * @return array
         */
        public function getCommissionApply($openid, $options = array(), $offset = 0, $limit = 20){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);

                if (empty( $mid )) {
                    return false;
                }
            }

            $result = array();

            $offset = $offset - 1;
            $offset = $offset < 0 ? 0 : intval($offset);

            if (in_array('all', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid ORDER BY `applytime` DESC ';

                $count = ' SELECT COUNT(id) FROM ' . tablename('ewei_shop_commission_apply');
                $count .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid';

                if (!empty( $limit )) {
                    $sql .= ' LIMIT ' . $offset . ',' . $limit;
                }

                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['allcount'] = pdo_fetchcolumn($count, $params);
                $result['all'] = pdo_fetchall($sql, $params);
            }

            // -1 无效 0 未知 1 正在申请 2 审核通过 3 已经打款
            if (in_array('invalid', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = -1 ORDER BY `applytime` DESC ';

                $count = ' SELECT COUNT(id) FROM ' . tablename('ewei_shop_commission_apply');
                $count .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = -1 ';

                if (!empty( $limit )) {
                    $sql .= ' LIMIT ' . $offset . ',' . $limit;
                }

                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['invalidcount'] = pdo_fetchcolumn($count, $params);
                $result['invalid'] = pdo_fetchall($sql, $params);
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 1 ORDER BY `applytime` DESC ';

                $count = ' SELECT COUNT(id) FROM ' . tablename('ewei_shop_commission_apply');
                $count .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 1 ';

                if (!empty( $limit )) {
                    $sql .= ' LIMIT ' . $offset . ',' . $limit;
                }

                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['applycount'] = pdo_fetchcolumn($count, $params);
                $result['apply'] = pdo_fetchall($sql, $params);
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 2 ORDER BY `applytime` DESC ';

                $count = ' SELECT COUNT(id) FROM ' . tablename('ewei_shop_commission_apply');
                $count .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 2 ';

                if (!empty( $limit )) {
                    $sql .= ' LIMIT ' . $offset . ',' . $limit;
                }

                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['checkcount'] = pdo_fetchcolumn($count, $params);
                $result['check'] = pdo_fetchall($sql, $params);
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 3 ORDER BY `applytime` DESC ';

                $count = ' SELECT COUNT(id) FROM ' . tablename('ewei_shop_commission_apply');
                $count .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 2 ';


                if (!empty( $limit )) {
                    $sql .= ' LIMIT ' . $offset . ',' . $limit;
                }

                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['paycount'] = pdo_fetchcolumn($count, $params);
                $result['pay'] = pdo_fetchall($sql, $params);
            }

            return $result;
        }

        /**
         * 提现申请审核
         * @param $openid
         * @param $lists
         * @param $apply
         * @return array|bool
         */
        public function checkCommissionApply($openid, $lists, $apply){
            global $_W, $_GPC;

            $member = m('member')->getMember($openid);

            if (empty( $member['id'] )) {
                return false;
            }

            if (!empty( $lists )) {

                $isAllUncheck = true;
                $time = time();
                $paycommission = 0;

                foreach ($lists as $list) {
                    if (!empty( $list['goods'] )) {
                        foreach ($list['goods'] as $goods) {

                            $c_status = $_GPC['c_status'][$goods['orderid']][$goods['goods_id']];
                            $c_content = $_GPC['c_content'][$goods['orderid']][$goods['goods_id']];

                            if (isset( $c_status ) && !empty( $c_status )) {

                                $data = array();

                                if ($c_status == 2) {
                                    $data = array( 'c_status' => $c_status, 'c_content' => $c_content, 'c_check_time' => $time );
                                    $isAllUncheck = false;
                                    $paycommission += $goods['c_menoy'];
                                } else if($c_status == -2){
                                    $data = array( 'c_status' => -2, 'c_content' => $c_content, 'c_check_time' => $time );
                                    $isAllUncheck = false;
                                }else{
                                    $data = array( 'c_status' => $c_status, 'c_content' => $c_content, 'c_invalid_time' => $time );
                                }

                                $status = pdo_update('ewei_shop_commission_record', $data, array( 'mid' => $member['id'], 'orderid' => $goods['orderid'], 'goods_id' => $goods['goods_id']));

                                if (empty( $status )) {
                                    $result = array( 'status' => 0, 'result' => '更新订单佣金状态失败，订单ID：' . $goods['orderid'] . ', 商品ID: ' . $goods['goods_id'] . ', 用户ID：' . $member['id'] );

                                    return $result;
                                }
                            }

                        }
                    }
                }

                if ($isAllUncheck) {
                    $status = pdo_update('ewei_shop_commission_apply', array( 'status' => -1, 'invalidtime' => $time ), array( 'id' => $apply['id'], 'uniacid' => $_W['uniacid'] ));
                } else {
                    $status = pdo_update('ewei_shop_commission_apply', array( 'status' => 2, 'checktime' => $time ), array( 'id' => $apply['id'], 'uniacid' => $_W['uniacid'] ));
                    $this->sendMessage($member['openid'], array( 'commission' => $paycommission, 'type' => $apply['type'] == 1 ? '微信' : '余额' ), TM_COMMISSION_CHECK);
                }

                if (!empty( $status )) {
                    $result = array( 'status' => 1, 'result' => '申请处理成功', );
                } else {
                    $result = array( 'status' => 0, 'result' => '申请处理失败', );
                }

                return $result;
            }

            return false;
        }

        /**
         * 撤销申请审核
         * @param $openid
         * @param $lists
         * @param $apply
         * @return array|bool
         */
        public function cancelCommissionApply($openid, $lists, $apply){
            global $_W;

            $member = m('member')->getMember($openid);

            if (empty( $member['id'] )) {
                return false;
            }

            if (!empty( $lists )) {

                foreach ($lists as $list) {
                    if (!empty( $list['goods'] )) {
                        foreach ($list['goods'] as $goods) {
                            $data = array( 'c_status' => 1, 'c_content' => '', 'c_check_time' => 0, 'c_invalid_time' => 0 );
                            pdo_update('ewei_shop_commission_record', $data, array( 'mid' => $member['id'], 'orderid' => $goods['orderid'], 'goods_id' => $goods['goods_id'], 'c_status' => array('!=' => -2) ));
                        }
                    }
                }

                $status = pdo_update('ewei_shop_commission_apply', array( 'status' => 1, 'invalidtime' => 0 ), array( 'id' => $apply['id'], 'uniacid' => $_W['uniacid'] ));

                if (!empty( $status )) {
                    $result = array( 'status' => 1, 'result' => '撤销申请处理成功', );
                } else {
                    $result = array( 'status' => 0, 'result' => '撤销申请处理失败', );
                }

                return $result;
            }

            return false;
        }

        /**
         * 佣金提现打款操作
         * @param $openid
         * @param $lists
         * @param $totalpay
         * @param $apply
         * @return array|bool
         */
        public function payCommissionApply($openid, $lists, $totalpay, $apply){
            global $_W, $_GPC;

            $member = m('member')->getMember($openid);

            if (empty( $member['id'] )) {
                return false;
            }

            if (!empty( $lists )) {

                $time = time();
                $pay = $totalpay;

                if ($apply['type'] == 1) {
                    $pay *= 100;
                }

                $status = m('finance')->pay($member['openid'], $apply['type'], $pay, $apply['applyno']);
                plog('commission.apply.pay', "佣金打款 ID: {$apply['id']} 申请编号: {$apply['applyno']} 审核通过佣金: {$totalpay} ");

                if (is_error($status)) {
                    $result = array( 'status' => 0, 'result' => $status['message'], );

                    return $result;
                }

                foreach ($lists as $list) {
                    if (!empty( $list['goods'] )) {
                        foreach ($list['goods'] as $goods) {
                            if ($goods['c_status'] == 2) {
                                $data = array( 'c_status' => 3, 'c_pay_time' => $time );

                                pdo_update('ewei_shop_commission_record', $data, array( 'mid' => $member['id'], 'orderid' => $goods['orderid'], 'goods_id' => $goods['goods_id'] ));
                            }
                        }
                    }
                }

                $status = pdo_update('ewei_shop_commission_apply', array( 'status' => 3, 'paytime' => $time ), array( 'id' => $apply['id'], 'uniacid' => $_W['uniacid'] ));

                if (!empty( $status )) {
                    $result = array( 'status' => 1, 'result' => '佣金打款处理成功', );
                } else {
                    $result = array( 'status' => 0, 'result' => '佣金打款处理失败', );
                }

                return $result;
            }

            return false;
        }

        /**
         * 获取某一提现记录的详细信息
         * @param $applyid
         * @return bool
         */
        public function getCommissionApplyDetail($applyid){
            global $_W;

            $sql = 'SELECT * FROM ' . tablename('ewei_shop_commission_apply');
            $sql .= ' WHERE `uniacid` = :uniacid AND `id` = :id ';

            return pdo_fetch($sql, array( ':uniacid' => $_W['uniacid'], ':id' => intval($applyid) ));
        }

        /**
         * 获取指定佣金申请，已付款的金额。
         * @param $openid
         * @param $applyid
         * @return string
         */
        public function getCommissionApplyPayPrice($openid, $applyid){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);
            }

            $apply = $this->getCommissionApplyDetail($applyid);
            $applyids = iunserializer($apply['orderids']);

            $sql = 'SELECT SUM(c_money) FROM ' . tablename('ewei_shop_commission_record');
            $sql .= ' WHERE `orderid` IN (' . implode(',', $applyids) . ') AND `uniacid` = :uniacid AND `mid` = :mid AND `c_status` = 3 ';

            $result = pdo_fetchcolumn($sql, array( ':uniacid' => $_W['uniacid'], ':mid' => $mid ));

            return number_format($result, 2);
        }

        /**
         * 获取提现记录里某一组订单的详细信息
         * @param $openid
         * @param array $orderids
         * @return array|bool
         */
        public function getCommissionApplyOrderDetail($openid, $orderids = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);

                if (empty( $mid )) {
                    return false;
                }
            }

            if (!empty( $orderids )) {
                $sql = ' SELECT * FROM ' . tablename('ewei_shop_order') . ' WHERE `id` IN (' . implode(',', $orderids) . ') AND `uniacid` = :uniacid ';
                $orderLists = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ));

                $totalpay = 0;
                $orderpay = 0;

                if (!empty( $orderLists )) {

                    $totalcommission = 0;
                    $totalorderprice = 0;

                    foreach ($orderLists as &$orderList) {

                        $sql = 'SELECT cr.*, g.id, g.title, g.thumb FROM ' . tablename('ewei_shop_commission_record') . ' AS cr ';
                        $sql .= 'LEFT JOIN ' . tablename('ewei_shop_goods') . ' AS g ON cr.goods_id = g.id ';
                        $sql .= 'WHERE  cr.uniacid = :uniacid AND cr.mid = :mid AND cr.orderid = :orderid ';
                        $sql .= 'ORDER BY cr.o_create_time DESC';

                        $goods = pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'], ':mid' => $mid, ':orderid' => $orderList['id'] ));
                        $goods = set_medias($goods, 'thumb');

                        $ordercommission = 0;

                        foreach ($goods as &$g) {

                            $g['goodsid'] = $g['id'];
                            $g['commission'] = $g['c_money'];
                            $totalcommission += $g['commission'];
                            $ordercommission += $g['commission'];
                            $totalorderprice += $g['cg_money'];

                            if ($g['c_status'] >= 2) {
                                $totalpay += $g['commission'];
                                $orderpay += $g['commission'];
                            }

                            if ($g['c_status'] == 1) {
                                $g['statusstr'] = '待审核';
                                $g['dealtime'] = date('Y-m-d H:i', $g['c_apply_time']);
                            } else {
                                if ($g['c_status'] == 2) {
                                    $g['statusstr'] = '待打款';
                                    $g['dealtime'] = date('Y-m-d H:i', $g['c_check_time']);
                                } else {
                                    if ($g['c_status'] == 3) {
                                        $g['statusstr'] = '已打款';
                                        $g['dealtime'] = date('Y-m-d H:i', $g['c_pay_time']);
                                    } else {
                                        if ($g['c_status'] == -1) {
                                            $g['statusstr'] = '无效';
                                            $g['dealtime'] = date('Y-m-d H:i', $g['c_invalid_time']);
                                        }else{
                                            if ($g['c_status'] == -2) {
                                                $orderpay = 0;
                                                $g['statusstr'] = '无 [退款]';
                                                $g['dealtime'] = date('Y-m-d H:i', $g['c_invalid_time']);
                                            }
                                        }
                                    }
                                }
                            }

                            $g['status'] = $g['c_status'];
                            $g['content'] = $g['c_content'];
                            $g['level'] = $g['c_rank'];

                            if ($g['level'] == 1) {
                                $g['level'] = '一';
                            } else {
                                if ($g['level'] == 2) {
                                    $g['level'] = '二';
                                } else {
                                    if ($g['level'] == 3) {
                                        $g['level'] = '三';
                                    }
                                }
                            }
                        }

                        unset( $g );

                        $orderList['goods'] = $goods;
                        $orderList['ordercommission'] = $ordercommission;
                        $orderList['orderpay'] = $orderpay;
                        $orderList['totalorderprice'] = $totalorderprice;
                    }
                    unset( $orderList );

                    return array( 'lists' => $orderLists, 'totalcommission' => $totalcommission, 'totalorderprice' => $totalorderprice, 'totalpay' => $totalpay );
                }
            }

            return false;
        }

        /**
         * 计算某种状态的佣金和
         * @param $openid
         * @param array $options
         * @return array
         */
        public function getCommissionApplySum($openid, $options = array()){
            global $_W;

            $mid = intval($openid);

            if (empty( $mid )) {
                $mid = m('member')->getMid($openid);

                if (empty( $mid )) {
                    return false;
                }
            }

            $result = array();

            if (in_array('all', $options)) {
                $sql = ' SELECT SUM(commission) FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` >= 0';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['all'] = pdo_fetchcolumn($sql, $params);
            }

            // -1 无效 0 未知 1 正在申请 2 审核通过 3 已经打款
            if (in_array('invalid', $options)) {
                $sql = ' SELECT SUM(commission) FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = -1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['invalid'] = pdo_fetchcolumn($sql, $params);
            }

            if (in_array('apply', $options)) {
                $sql = ' SELECT SUM(commission) FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 1';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['apply'] = pdo_fetchcolumn($sql, $params);
            }

            if (in_array('check', $options)) {
                $sql = ' SELECT SUM(commission) FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 2';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['check'] = pdo_fetchcolumn($sql, $params);
            }

            if (in_array('pay', $options)) {
                $sql = ' SELECT SUM(commission) FROM ' . tablename('ewei_shop_commission_apply');
                $sql .= ' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `status` = 3';
                $params = array( ':uniacid' => $_W['uniacid'], ':mid' => $mid );

                $result['pay'] = pdo_fetchcolumn($sql, $params);
            }

            return $result;
        }

        /**
         * 订单佣金计算
         * @param int $orderid
         * @param bool $update
         * @return array
         */
        public function calculate($orderid = 0, $update = true){
            global $_W;
            $set = $this->getSet();
            $levels = $this->getLevels();

            $goodsSql = ' select og.id,og.realprice,og.total,g.hascommission, g.commission1_rate,g.commission1_pay,g.commission2_rate,g.commission2_pay,g.commission3_rate,g.commission3_pay from ' . tablename('ewei_shop_order_goods') . ' as og ';
            $goodsSql .= ' left join ' . tablename('ewei_shop_goods') . ' as g on g.id = og.goodsid ';
            $goodsSql .= ' where og.orderid=:orderid and og.uniacid=:uniacid';

            $goods = pdo_fetchall($goodsSql, array( ':orderid' => $orderid, ':uniacid' => $_W['uniacid'] ));

            if ($set['level'] > 0) {
                foreach ($goods as &$cinfo) {

                    $price = $cinfo['realprice'];

                    if ($cinfo['hascommission'] == 1) {
                        $cinfo['commission1'] = array( 'default' => $set['level'] >= 1 ? $cinfo['commission1_rate'] > 0 ? round($cinfo['commission1_rate'] * $price / 100, 2) . "" : round($cinfo['commission1_pay'] * $cinfo['total'], 2) : 0 );
                        $cinfo['commission2'] = array( 'default' => $set['level'] >= 2 ? $cinfo['commission2_rate'] > 0 ? round($cinfo['commission2_rate'] * $price / 100, 2) . "" : round($cinfo['commission2_pay'] * $cinfo['total'], 2) : 0 );
                        $cinfo['commission3'] = array( 'default' => $set['level'] >= 3 ? $cinfo['commission3_rate'] > 0 ? round($cinfo['commission3_rate'] * $price / 100, 2) . "" : round($cinfo['commission3_pay'] * $cinfo['total'], 2) : 0 );
                    } else {
                        $cinfo['commission1'] = array( 'default' => $set['level'] >= 1 ? round($set['commission1'] * $price / 100, 2) . "" : 0 );
                        $cinfo['commission2'] = array( 'default' => $set['level'] >= 2 ? round($set['commission2'] * $price / 100, 2) . "" : 0 );
                        $cinfo['commission3'] = array( 'default' => $set['level'] >= 3 ? round($set['commission3'] * $price / 100, 2) . "" : 0 );

                        foreach ($levels as $level) {
                            $cinfo['commission1']['level' . $level['id']] = $set['level'] >= 1 ? round($level['commission1'] * $price / 100, 2) . "" : 0;
                            $cinfo['commission2']['level' . $level['id']] = $set['level'] >= 2 ? round($level['commission2'] * $price / 100, 2) . "" : 0;
                            $cinfo['commission3']['level' . $level['id']] = $set['level'] >= 3 ? round($level['commission3'] * $price / 100, 2) . "" : 0;
                        }
                    }
                    if ($update) {
                        pdo_update('ewei_shop_order_goods', array( 'commission1' => iserializer($cinfo['commission1']), 'commission2' => iserializer($cinfo['commission2']), 'commission3' => iserializer($cinfo['commission3']) ), array( 'id' => $cinfo['id'] ));
                    }
                }
                unset( $cinfo );
            }
            return $goods;
        }

        /**
         * 获取佣金（单数，金额）信息
         * @param $openid
         * @param null $options
         * @return mixed
         */
        public function getInfo($openid, $options = null){

            if (empty( $options ) || !is_array($options)) {
                $options = array();
            }
            global $_W;
            $set = $this->getSet();
            $level = intval($set['level']);
            $member = m('member')->getInfo($openid);
            $agentLevel = $this->getLevel($openid);
            $time = time();
            $day_times = intval($set['settledays']) * 3600 * 24;
            $agentcount = 0;
            $ordercount0 = 0;
            $ordermoney0 = 0;
            $ordercount = 0;
            $ordermoney = 0;
            $ordercount3 = 0;
            $ordermoney3 = 0;
            $commission_total = 0;
            $commission_ok = 0;
            $commission_apply = 0;
            $commission_check = 0;
            $commission_lock = 0;
            $commission_pay = 0;
            $level1 = 0;
            $level2 = 0;
            $level3 = 0;
            $order10 = 0;
            $order20 = 0;
            $order30 = 0;
            $order1 = 0;
            $order2 = 0;
            $order3 = 0;
            $order13 = 0;
            $order23 = 0;
            $order33 = 0;

            $level1_agentids = array();
            $level2_agentids = array();
            $level3_agentids = array();

            if ($level >= 1) {
                if (in_array('ordercount0', $options)) {
                    $level1_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid=:agentid and o.status>=0 and og.status1>=0 and o.uniacid=:uniacid  limit 1', array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    $order10 += $level1_ordercount['ordercount'];
                    $ordercount0 += $level1_ordercount['ordercount'];
                    $ordermoney0 += $level1_ordercount['ordermoney'];
                }
                if (in_array('ordercount', $options)) {
                    $level1_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid=:agentid and o.status>=1 and og.status1>=0 and o.uniacid=:uniacid  limit 1', array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    $order1 += $level1_ordercount['ordercount'];
                    $ordercount += $level1_ordercount['ordercount'];
                    $ordermoney += $level1_ordercount['ordermoney'];
                }
                if (in_array('ordercount3', $options)) {
                    $level1_ordercount3 = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid=:agentid and o.status>=3 and og.status1>=0 and o.uniacid=:uniacid  limit 1', array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    $order13 += $level1_ordercount3['ordercount'];
                    $ordercount3 += $level1_ordercount3['ordercount'];
                    $ordermoney3 += $level1_ordercount3['ordermoney'];
                }
                if (in_array('total', $options)) {
                    $level1_commissions = pdo_fetchall('select og.commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    foreach ($level1_commissions as $c) {
                        $commission = iunserializer($c['commission1']);
                        $commission_total += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                    }
                }
                if (in_array('ok', $options)) {
                    $level1_commissions = pdo_fetchall('select og.commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and ({$time} - o.createtime > {$day_times}) and og.status1=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    foreach ($level1_commissions as $c) {
                        $commission = iunserializer($c['commission1']);
                        $commission_ok += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                    }
                }
                if (in_array('lock', $options)) {
                    $level1_commissions1 = pdo_fetchall('select og.commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and ({$time} - o.createtime <= {$day_times})  and og.status1=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    foreach ($level1_commissions1 as $c) {
                        $commission = iunserializer($c['commission1']);
                        $commission_lock += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                    }
                }
                if (in_array('apply', $options)) {
                    $level1_commissions2 = pdo_fetchall('select og.commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and og.status1=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    foreach ($level1_commissions2 as $c) {
                        $commission = iunserializer($c['commission1']);
                        $commission_apply += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                    }
                }
                if (in_array('check', $options)) {
                    $level1_commissions2 = pdo_fetchall('select og.commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and og.status1=2 and o.uniacid=:uniacid ", array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    foreach ($level1_commissions2 as $c) {
                        $commission = iunserializer($c['commission1']);
                        $commission_check += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                    }
                }
                if (in_array('pay', $options)) {
                    $level1_commissions2 = pdo_fetchall('select og.commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . " where o.agentid=:agentid and o.status>=3 and og.status1=3 and o.uniacid=:uniacid ", array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ));
                    foreach ($level1_commissions2 as $c) {
                        $commission = iunserializer($c['commission1']);
                        $commission_pay += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                    }
                }
                $level1_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where agentid=:agentid and isagent=1 and status=1 and uniacid=:uniacid ', array( ':uniacid' => $_W['uniacid'], ':agentid' => $member['id'] ), 'id');
                $level1 = count($level1_agentids);
                $agentcount += $level1;
            }
            if ($level >= 2) {
                if ($level1 > 0) {
                    if (in_array('ordercount0', $options)) {
                        $level2_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ')  and o.status>=0 and og.status2>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'] ));
                        $order20 += $level2_ordercount['ordercount'];
                        $ordercount0 += $level2_ordercount['ordercount'];
                        $ordermoney0 += $level2_ordercount['ordermoney'];
                    }
                    if (in_array('ordercount', $options)) {
                        $level2_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ')  and o.status>=1 and og.status2>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'] ));
                        $order2 += $level2_ordercount['ordercount'];
                        $ordercount += $level2_ordercount['ordercount'];
                        $ordermoney += $level2_ordercount['ordermoney'];
                    }
                    if (in_array('ordercount3', $options)) {
                        $level2_ordercount3 = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct o.id) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ')  and o.status>=3 and og.status2>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'] ));
                        $order23 += $level2_ordercount3['ordercount'];
                        $ordercount3 += $level2_ordercount3['ordercount'];
                        $ordermoney3 += $level2_ordercount3['ordermoney'];
                    }
                    if (in_array('total', $options)) {
                        $level2_commissions = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level2_commissions as $c) {
                            $commission = iunserializer($c['commission2']);
                            $commission_total += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('ok', $options)) {
                        $level2_commissions = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status2=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level2_commissions as $c) {
                            $commission = iunserializer($c['commission2']);
                            $commission_ok += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('lock', $options)) {
                        $level2_commissions1 = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and ({$time} - o.createtime <= {$day_times}) and og.status2=0 and o.status>=3  and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level2_commissions1 as $c) {
                            $commission = iunserializer($c['commission2']);
                            $commission_lock += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('apply', $options)) {
                        $level2_commissions2 = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=3 and og.status2=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level2_commissions2 as $c) {
                            $commission = iunserializer($c['commission2']);
                            $commission_apply += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('check', $options)) {
                        $level2_commissions3 = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=3 and og.status2=2 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level2_commissions3 as $c) {
                            $commission = iunserializer($c['commission2']);
                            $commission_check += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('pay', $options)) {
                        $level2_commissions3 = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where o.agentid in( ' . implode(',', array_keys($level1_agentids)) . ")  and o.status>=3 and og.status2=3 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level2_commissions3 as $c) {
                            $commission = iunserializer($c['commission2']);
                            $commission_pay += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    $level2_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where agentid in( ' . implode(',', array_keys($level1_agentids)) . ') and isagent=1 and status=1 and uniacid=:uniacid', array( ':uniacid' => $_W['uniacid'] ), 'id');
                    $level2 = count($level2_agentids);
                    $agentcount += $level2;
                }
            }
            if ($level >= 3) {
                if ($level2 > 0) {
                    if (in_array('ordercount0', $options)) {
                        $level3_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct og.orderid) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ')  and o.status>=0 and og.status3>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'] ));
                        $order30 += $level3_ordercount['ordercount'];
                        $ordercount0 += $level3_ordercount['ordercount'];
                        $ordermoney0 += $level3_ordercount['ordermoney'];
                    }
                    if (in_array('ordercount', $options)) {
                        $level3_ordercount = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct og.orderid) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ')  and o.status>=1 and og.status3>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'] ));
                        $order3 += $level3_ordercount['ordercount'];
                        $ordercount += $level3_ordercount['ordercount'];
                        $ordermoney += $level3_ordercount['ordermoney'];
                    }
                    if (in_array('ordercount3', $options)) {
                        $level3_ordercount3 = pdo_fetch('select sum(og.realprice) as ordermoney,count(distinct og.orderid) as ordercount from ' . tablename('ewei_shop_order') . ' o ' . ' left join  ' . tablename('ewei_shop_order_goods') . ' og on og.orderid=o.id ' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ')  and o.status>=3 and og.status3>=0 and o.uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'] ));
                        $order33 += $level3_ordercount3['ordercount'];
                        $ordercount3 += $level3_ordercount3['ordercount'];
                        $ordermoney3 += $level3_ordercount3['ordermoney'];
                    }
                    if (in_array('total', $options)) {
                        $level3_commissions = pdo_fetchall('select commission3  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level3_commissions as $c) {
                            $commission = iunserializer($c['commission3']);
                            $commission_total += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('ok', $options)) {
                        $level3_commissions = pdo_fetchall('select commission3  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and ({$time} - o.createtime > {$day_times}) and o.status>=3 and og.status3=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level3_commissions as $c) {
                            $commission = iunserializer($c['commission3']);
                            $commission_ok += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('lock', $options)) {
                        $level3_commissions1 = pdo_fetchall('select commission3  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and ({$time} - o.createtime > {$day_times}) and og.status3=0  and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level3_commissions1 as $c) {
                            $commission = iunserializer($c['commission3']);
                            $commission_lock += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('apply', $options)) {
                        $level3_commissions2 = pdo_fetchall('select commission3  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and og.status3=1 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level3_commissions2 as $c) {
                            $commission = iunserializer($c['commission3']);
                            $commission_lock += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('check', $options)) {
                        $level3_commissions3 = pdo_fetchall('select commission3  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and og.status3=2 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level3_commissions3 as $c) {
                            $commission = iunserializer($c['commission3']);
                            $commission_check += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    if (in_array('pay', $options)) {
                        $level3_commissions3 = pdo_fetchall('select commission3  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid' . ' where o.agentid in( ' . implode(',', array_keys($level2_agentids)) . ")  and o.status>=3 and og.status3=3 and o.uniacid=:uniacid", array( ':uniacid' => $_W['uniacid'] ));
                        foreach ($level3_commissions3 as $c) {
                            $commission = iunserializer($c['commission3']);
                            $commission_pay += isset( $commission['level' . $agentLevel['id']] ) ? $commission['level' . $agentLevel['id']] : $commission['default'];
                        }
                    }
                    $level3_agentids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where uniacid=:uniacid and agentid in( ' . implode(',', array_keys($level2_agentids)) . ') and isagent=1 and status=1', array( ':uniacid' => $_W['uniacid'] ), 'id');
                    $level3 = count($level3_agentids);
                    $agentcount += $level3;
                }
            }

            $member['agentcount'] = $agentcount;
            $member['ordercount'] = $ordercount;
            $member['ordermoney'] = $ordermoney;
            $member['order1'] = $order1;
            $member['order2'] = $order2;
            $member['order3'] = $order3;
            $member['ordercount3'] = $ordercount3;
            $member['ordermoney3'] = $ordermoney3;
            $member['order13'] = $order13;
            $member['order23'] = $order23;
            $member['order33'] = $order33;
            $member['ordercount0'] = $ordercount0;
            $member['ordermoney0'] = $ordermoney0;
            $member['order10'] = $order10;
            $member['order20'] = $order20;
            $member['order30'] = $order30;
            $member['commission_total'] = round($commission_total, 2);
            $member['commission_ok'] = round($commission_ok, 2);
            $member['commission_lock'] = round($commission_lock, 2);
            $member['commission_apply'] = round($commission_apply, 2);
            $member['commission_check'] = round($commission_check, 2);
            $member['commission_pay'] = round($commission_pay, 2);
            $member['level1'] = $level1;
            $member['level1_agentids'] = $level1_agentids;
            $member['level2'] = $level2;
            $member['level2_agentids'] = $level2_agentids;
            $member['level3'] = $level3;
            $member['level3_agentids'] = $level3_agentids;
            $member['agenttime'] = date('Y-m-d H:i', $member['agenttime']);

            return $member;
        }

        /**
         * 获取此订单涉及到的分销用户
         * @param int $orderid
         * @return array
         */
        public function getAgents($orderid = 0){
            global $_W, $_GPC;
            $agents = array();
            $order = pdo_fetch('select id,agentid,openid from ' . tablename('ewei_shop_order') . ' where id=:id and uniacid=:uniacid limit 1', array( ':id' => $orderid, ':uniacid' => $_W['uniacid'] ));
            if (empty( $order )) {
                return $agents;
            }
            $m1 = m('member')->getInfo($order['agentid']);

            if (!empty( $m1 ) && $m1['isagent'] == 1 && $m1['status'] == 1) {
                $agents[] = $m1;
                if (!empty( $m1['agentid'] )) {
                    $m2 = m('member')->getInfo($m1['agentid']);
                    if (!empty( $m2 ) && $m2['isagent'] == 1 && $m2['status'] == 1) {
                        $agents[] = $m2;
                        if (!empty( $m2['agentid'] )) {
                            $m3 = m('member')->getInfo($m2['agentid']);
                            if (!empty( $m3 ) && $m3['isagent'] == 1 && $m3['status'] == 1) {
                                $agents[] = $m3;
                            }
                        }
                    }
                }
            }
            return $agents;
        }

        /**
         * 判断用户是否为分销商
         * @param $openid
         * @return bool
         */
        public function isAgent($openid){
            if (empty( $openid )) {
                return false;
            }
            if (is_array($openid)) {
                return $openid['isagent'] == 1 && $openid['status'] == 1;
            }
            $member = m('member')->getMember($openid);
            return $member['isagent'] == 1 && $member['status'] == 1;
        }

        /**
         * 获取商品可能带来的分销佣金
         * @param $goods
         * @return float|int
         */
        public function getCommission($goods){
            global $_W;
            $set = $this->getSet();
            $commission = 0;
            if ($goods['hascommission'] == 1) {
                $commission = $set['level'] >= 1 ? $goods['commission1_rate'] > 0 ? $goods['commission1_rate'] * $goods['marketprice'] / 100 : $goods['commission1_pay'] : 0;
            } else {
                $openid = m('user')->getOpenid();
                $level = $this->getLevel($openid);
                if (!empty( $level )) {
                    $commission = $set['level'] >= 1 ? round($level['commission1'] * $goods['marketprice'] / 100, 2) : 0;
                } else {
                    $commission = $set['level'] >= 1 ? round($set['commission1'] * $goods['marketprice'] / 100, 2) : 0;
                }
            }
            return $commission;
        }

        /**
         * 生成小店二维码
         * @param int $mid
         * @param int $posterid
         * @return string
         */
        public function createMyShopQrcode($mid = 0, $posterid = 0){
            global $_W;
            $path = IA_ROOT . "/addons/ewei_shop/data/qrcode/" . $_W['uniacid'];
            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path);
            }
            $url = $_W['siteroot'] . 'app/index.php?i=' . $_W['uniacid'] . '&j=' . $_W['acid'] . '&c=entry&m=ewei_shop&do=plugin&p=commission&method=myshop&mid=' . $mid;
            if (!empty( $posterid )) {
                $url .= '&posterid=' . $posterid;
            }
            $file = 'myshop_' . $posterid . '_' . $mid . '.png';
            $qr_file = $path . '/' . $file;
            if (!is_file($qr_file)) {
                require IA_ROOT . '/framework/library/qrcode/phpqrcode.php';
                QRcode::png($url, $qr_file, QR_ECLEVEL_H, 4);
            }
            return $_W['siteroot'] . 'addons/ewei_shop/data/qrcode/' . $_W['uniacid'] . '/' . $file;
        }

        private function createImage($url){
            load()->func('communication');
            $resp = ihttp_request($url);
            return imagecreatefromstring($resp['content']);
        }

        /**
         * 生成商品二维码
         * @param $goods
         * @param $shop_set
         * @return string
         */
        public function createGoodsImage($goods, $shop_set){
            global $_W, $_GPC;
            $goods = set_medias($goods, 'thumb');
            $openid = m('user')->getOpenid();
            $me = m('member')->getInfo($openid);
            if ($me['isagent'] == 1 && $me['status'] == 1) {
                $userinfo = $me;
            } else {
                $mid = intval($_GPC['mid']);
                if (!empty( $mid )) {
                    $userinfo = m('member')->getInfo($mid);
                }
            }
            $path = IA_ROOT . "/addons/ewei_shop/data/poster/" . $_W['uniacid'] . '/';
            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path);
            }
            $img = empty( $goods['commission_thumb'] ) ? $goods['thumb'] : tomedia($goods['commission_thumb']);
            $md5 = md5(json_encode(array( 'id' => $goods['id'], 'marketprice' => $goods['marketprice'], 'productprice' => $goods['productprice'], 'img' => $img, 'openid' => $openid, 'version' => 4 )));
            $file = $md5 . '.jpg';
            if (!is_file($path . $file)) {
                set_time_limit(0);
                $font = IA_ROOT . "/addons/ewei_shop/static/fonts/msyh.ttf";
                $target = imagecreatetruecolor(640, 1225);
                $bg = imagecreatefromjpeg(IA_ROOT . '/addons/ewei_shop/plugin/commission/images/poster.jpg');
                imagecopy($target, $bg, 0, 0, 0, 0, 640, 1225);
                imagedestroy($bg);
                $avatar = preg_replace('/\/0$/i', '/96', $userinfo['avatar']);
                $head = $this->createImage($avatar);
                $w = imagesx($head);
                $h = imagesy($head);
                imagecopyresized($target, $head, 24, 32, 0, 0, 88, 88, $w, $h);
                imagedestroy($head);
                $thumb = $this->createImage($img);
                $w = imagesx($thumb);
                $h = imagesy($thumb);
                imagecopyresized($target, $thumb, 0, 160, 0, 0, 640, 640, $w, $h);
                imagedestroy($thumb);
                $black = imagecreatetruecolor(640, 127);
                imagealphablending($black, false);
                imagesavealpha($black, true);
                $blackcolor = imagecolorallocatealpha($black, 0, 0, 0, 25);
                imagefill($black, 0, 0, $blackcolor);
                imagecopy($target, $black, 0, 678, 0, 0, 640, 127);
                imagedestroy($black);
                $goods_qrcode_file = tomedia(m('qrcode')->createGoodsQrcode($userinfo['id'], $goods['id']));
                $qrcode = $this->createImage($goods_qrcode_file);
                $w = imagesx($qrcode);
                $h = imagesy($qrcode);
                imagecopyresized($target, $qrcode, 50, 835, 0, 0, 250, 250, $w, $h);
                imagedestroy($qrcode);
                $bc = imagecolorallocate($target, 0, 3, 51);
                $cc = imagecolorallocate($target, 240, 102, 0);
                $wc = imagecolorallocate($target, 255, 255, 255);
                $yc = imagecolorallocate($target, 255, 255, 0);
                $str1 = '我是';
                imagettftext($target, 20, 0, 150, 70, $bc, $font, $str1);
                imagettftext($target, 20, 0, 210, 70, $cc, $font, $userinfo['nickname']);
                $str2 = '我要为';
                imagettftext($target, 20, 0, 150, 105, $bc, $font, $str2);
                $str3 = $shop_set['name'];
                imagettftext($target, 20, 0, 240, 105, $cc, $font, $str3);
                $box = imagettfbbox(20, 0, $font, $str3);
                $width = $box[4] - $box[6];
                $str4 = '代言';
                imagettftext($target, 20, 0, 240 + $width + 10, 105, $bc, $font, $str4);
                $str5 = mb_substr($goods['title'], 0, 50, 'utf-8');
                imagettftext($target, 20, 0, 30, 730, $wc, $font, $str5);
                $str6 = "￥" . number_format($goods['marketprice'], 2);
                imagettftext($target, 25, 0, 25, 780, $yc, $font, $str6);
                $box = imagettfbbox(26, 0, $font, $str6);
                $width = $box[4] - $box[6];
                if ($goods['productprice'] > 0) {
                    $str7 = "￥" . number_format($goods['productprice'], 2);
                    imagettftext($target, 22, 0, 25 + $width + 10, 780, $wc, $font, $str7);
                    $end = 25 + $width + 10;
                    $box = imagettfbbox(22, 0, $font, $str7);
                    $width = $box[4] - $box[6];
                    imageline($target, $end, 770, $end + $width + 20, 770, $wc);
                    imageline($target, $end, 771.5, $end + $width + 20, 771, $wc);
                }
                imagejpeg($target, $path . $file);
                imagedestroy($target);
            }
            return $_W['siteroot'] . "addons/ewei_shop/data/poster/" . $_W['uniacid'] . "/" . $file;
        }

        public function createShopImage($shop_set){
            global $_W, $_GPC;
            $shop_set = set_medias($shop_set, 'signimg');
            $path = IA_ROOT . "/addons/ewei_shop/data/poster/" . $_W['uniacid'] . '/';
            if (!is_dir($path)) {
                load()->func('file');
                mkdirs($path);
            }
            $mid = intval($_GPC['mid']);
            $openid = m('user')->getOpenid();
            $me = m('member')->getInfo($openid);
            if ($me['isagent'] == 1 && $me['status'] == 1) {
                $userinfo = $me;
            } else {
                $mid = intval($_GPC['mid']);
                if (!empty( $mid )) {
                    $userinfo = m('member')->getInfo($mid);
                }
            }
            $md5 = md5(json_encode(array( 'openid' => $openid, 'signimg' => $shop_set['signimg'], 'version' => 4 )));
            $file = $md5 . '.jpg';
            if (!is_file($path . $file)) {
                set_time_limit(0);
                @ini_set('memory_limit', '256M');
                $font = IA_ROOT . "/addons/ewei_shop/static/fonts/msyh.ttf";
                $target = imagecreatetruecolor(640, 1225);
                $bc = imagecolorallocate($target, 0, 3, 51);
                $cc = imagecolorallocate($target, 240, 102, 0);
                $wc = imagecolorallocate($target, 255, 255, 255);
                $yc = imagecolorallocate($target, 255, 255, 0);
                $bg = imagecreatefromjpeg(IA_ROOT . '/addons/ewei_shop/plugin/commission/images/poster.jpg');
                imagecopy($target, $bg, 0, 0, 0, 0, 640, 1225);
                imagedestroy($bg);
                $avatar = preg_replace('/\/0$/i', '/96', $userinfo['avatar']);
                $head = $this->createImage($avatar);
                $w = imagesx($head);
                $h = imagesy($head);
                imagecopyresized($target, $head, 24, 32, 0, 0, 88, 88, $w, $h);
                imagedestroy($head);
                $thumb = $this->createImage($shop_set['signimg']);
                $w = imagesx($thumb);
                $h = imagesy($thumb);
                imagecopyresized($target, $thumb, 0, 160, 0, 0, 640, 640, $w, $h);
                imagedestroy($thumb);
                $qrcode_file = tomedia($this->createMyShopQrcode($userinfo['id']));
                $qrcode = $this->createImage($qrcode_file);
                $w = imagesx($qrcode);
                $h = imagesy($qrcode);
                imagecopyresized($target, $qrcode, 50, 835, 0, 0, 250, 250, $w, $h);
                imagedestroy($qrcode);
                $str1 = '我是';
                imagettftext($target, 20, 0, 150, 70, $bc, $font, $str1);
                imagettftext($target, 20, 0, 210, 70, $cc, $font, $userinfo['nickname']);
                $str2 = '我要为';
                imagettftext($target, 20, 0, 150, 105, $bc, $font, $str2);
                $str3 = $shop_set['name'];
                imagettftext($target, 20, 0, 240, 105, $cc, $font, $str3);
                $box = imagettfbbox(20, 0, $font, $str3);
                $width = $box[4] - $box[6];
                $str4 = '代言';
                imagettftext($target, 20, 0, 240 + $width + 10, 105, $bc, $font, $str4);
                imagejpeg($target, $path . $file);
                imagedestroy($target);
            }
            return $_W['siteroot'] . "addons/ewei_shop/data/poster/" . $_W['uniacid'] . "/" . $file;
        }

        public function checkAgent(){
            global $_W, $_GPC;
            $set = $this->getSet();
            if (empty( $set['level'] )) {
                return;
            }
            $openid = m('user')->getOpenid();
            if (empty( $openid )) {
                return;
            }
            $member = m('member')->getMember($openid);
            if (empty( $member )) {
                return;
            }
            $parent = false;
            $mid = intval($_GPC['mid']);
            if (!empty( $mid )) {
                $parent = m('member')->getMember($mid);
            }
            $parent_is_agent = !empty( $parent ) && $parent['isagent'] == 1 && $parent['status'] == 1;
            if ($parent_is_agent) {
                if ($parent['openid'] != $openid) {
                    $clickcount = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_commission_clickcount') . ' where uniacid=:uniacid and openid=:openid and from_openid=:from_openid limit 1', array( ':uniacid' => $_W['uniacid'], ':openid' => $openid, ':from_openid' => $parent['openid'] ));
                    if ($clickcount <= 0) {
                        $click = array( 'uniacid' => $_W['uniacid'], 'openid' => $openid, 'from_openid' => $parent['openid'], 'clicktime' => time() );
                        pdo_insert('ewei_shop_commission_clickcount', $click);
                        pdo_update('ewei_shop_member', array( 'clickcount' => $parent['clickcount'] + 1 ), array( 'uniacid' => $_W['uniacid'], 'id' => $parent['id'] ));
                    }
                }
            }
            if ($this->isAgent($openid)) {
                return;
            }

            // 第一个用户，将自动成为分销商。
            if (true) {
                $first = pdo_fetchcolumn('select count(id) from ' . tablename('ewei_shop_member') . ' where id<:id and uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'], ':id' => $member['id'] ));
                if ($first <= 0) {
                    pdo_update('ewei_shop_member', array( 'isagent' => 1, 'status' => 1, 'agenttime' => time() ), array( 'uniacid' => $_W['uniacid'], 'id' => $member['id'] ));
                    return;
                }
            }

            $time = time();
            $become_child = intval($set['become_child']);
            if ($parent_is_agent) {
                if (empty( $become_child )) {
                    if (empty( $member['agentid'] ) && $member['id'] != $parent['id']) {
                        pdo_update('ewei_shop_member', array( 'agentid' => $parent['id'], 'childtime' => $time ), array( 'uniacid' => $_W['uniacid'], 'id' => $member['id'] ));
                        $this->sendMessage($parent['openid'], array( 'nickname' => $member['nickname'], 'childtime' => $time ), TM_COMMISSION_AGENT_NEW);
                    }
                } else {
                    if (empty( $member['agentid'] ) && $member['id'] != $parent['id']) {
                        pdo_update('ewei_shop_member', array( 'inviter' => $parent['id'] ), array( 'uniacid' => $_W['uniacid'], 'id' => $member['id'] ));
                    }
                }
            }
            $become_check = intval($set['become_check']);
            if (empty( $set['become'] )) {
                if ($parent_is_agent) {
                    pdo_update('ewei_shop_member', array( 'isagent' => 1, 'status' => $become_check, 'agenttime' => $become_check == 1 ? $time : 0 ), array( 'uniacid' => $_W['uniacid'], 'id' => $member['id'] ));
                    if ($become_check == 1) {
                        $this->sendMessage($openid, array( 'nickname' => $member['nickname'], 'agenttime' => $time ), TM_COMMISSION_BECOME);
                    }
                }
            }
        }

        /**
         * 订单确认检测
         * @param int $orderid
         * @return bool|void
         */
        public function checkOrderConfirm($orderid = 0){
            global $_W;

            $set = $this->getSet();

            if (!empty( $set['level'] ) && !empty( $orderid )) {

                $filed = array( 'id', 'openid', 'ordersn', 'goodsprice', 'agentid' );
                $order = m('order')->getOrderInfo($orderid, $filed);

                if (!empty( $order )) {
                    $time = time();
                    $openid = $order['openid'];
                    $member = m('member')->getMember($openid);

                    if (!empty( $member )) {

                        $become_child = intval($set['become_child']);

                        if (empty( $become_child )) {
                            $parent = m('member')->getMember($member['agentid']);
                        } else {
                            if(!empty($member['agentid'])){
                                $parent = m('member')->getMember($member['agentid']);
                            }else{
                                $parent = m('member')->getMember($member['inviter']);
                            }
                        }

                        $parent_is_agent = !empty( $parent ) && $parent['isagent'] == 1 && $parent['status'] == 1;
                        $become_child = intval($set['become_child']);

                        if ($parent_is_agent) {
                            if ($become_child == 1) {
                                if (empty( $member['agentid'] ) && $member['id'] != $parent['id']) {
                                    pdo_update('ewei_shop_member', array( 'agentid' => $parent['id'], 'childtime' => $time ), array( 'uniacid' => $_W['uniacid'], 'id' => $member['id'] ));

                                    pdo_update('ewei_shop_order', array( 'agentid' => $parent['id'] ), array( 'id' => $orderid ));
                                    $this->sendMessage($parent['openid'], array( 'nickname' => $member['nickname'], 'childtime' => $time ), TM_COMMISSION_AGENT_NEW);
                                }
                            }
                        }

                        // 购买者为分销商，且开启自购，则订单的上级为自己。
                        if ($member['isagent'] == 1 && $member['status'] == 1 && $set['selfbuy'] == 1) {
                            pdo_update('ewei_shop_order', array( 'agentid' => $member['id'] ), array( 'id' => $orderid ));
                        }else{
                            if($parent_is_agent){
                                pdo_update('ewei_shop_order', array( 'agentid' => $parent['id'] ), array( 'id' => $orderid ));
                            }
                        }

                        $this->getCalculate($orderid, true);    // 佣金计算
                    }

                }
            }

            return false;
        }

        /**
         * 订单发货检测
         * @param int $orderid
         * @return bool
         */
        public function checkOrderSend($orderid = 0){
            global $_W;

            if(!empty($orderid)){
                $this->_updateRecordOrderStatus($orderid, 'send');   // 修改佣金记录的状态。
            }

            return false;
        }

        /**
         * 订单支付检测
         * @param int $orderid
         * @return bool
         */
        public function checkOrderPay($orderid = 0){
            global $_W;

            $set = $this->getSet();

            if (!empty( $orderid ) && !empty( $set ['level'] )) {
                $filed = array( 'id', 'openid', 'ordersn', 'goodsprice', 'agentid', 'paytime' );
                $order = m('order')->getOrderInfo($orderid, $filed);

                if (!empty( $order )) {
                    $openid = $order ['openid'];
                    $member = m('member')->getMember($openid);

                    if (!empty( $member )) {
                        $time = time();
                        $become_child = intval($set ['become_child']);

                        if (empty( $become_child )) {
                            $parent = m('member')->getMember($member ['agentid']);
                        } else {
                            $parent = m('member')->getMember($member ['inviter']);
                        }

                        $parent_is_agent = !empty( $parent ) && $parent ['isagent'] == 1 && $parent ['status'] == 1;

                        if ($parent_is_agent) {
                            if ($become_child == 2) {
                                if (empty( $member ['agentid'] ) && $member ['id'] != $parent ['id']) {

                                    $member ['agentid'] = $parent ['id'];
                                    pdo_update('ewei_shop_member', array( 'agentid' => $parent ['id'], 'childtime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));
                                    $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'childtime' => $time ), TM_COMMISSION_AGENT_NEW);

                                    if (empty( $order ['agentid'] )) {
                                        $order ['agentid'] = $parent ['id'];
                                        pdo_update('ewei_shop_order', array( 'agentid' => $parent ['id'] ), array( 'id' => $orderid ));

                                        $this->getCalculate($order['id'], true);    // 上级为空，且发生变化时，佣金需要重新计算
                                    }
                                }
                            }
                        }

                        $this->_updateRecordOrderStatus($orderid, 'pay');   // 修改佣金记录的状态。

                        $isagent = $member ['isagent'] == 1 && $member ['status'] == 1;

                        if (!$isagent && empty( $set ['become_order'] )) {
                            $time = time();

                            if ($set ['become'] == 2 || $set ['become'] == 3) {
                                if (!empty( $member ['agentid'] )) {
                                    $parent = m('member')->getMember($member ['agentid']);
                                    if (empty( $parent ) || $parent ['isagent'] != 1 || $parent ['status'] != 1) {
                                        return false;
                                    }
                                }

                                if ($set ['become'] == '2') {
                                    $sql = 'SELECT COUNT(id) FROM ' . tablename('ewei_shop_order') . ' WHERE openid = :openid AND status >= 1 AND uniacid = :uniacid LIMIT 1';
                                    $ordercount = pdo_fetchcolumn($sql, array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid ));
                                    $can = $ordercount >= intval($set ['become_ordercount']);
                                } else if ($set ['become'] == '3') {
                                    $sql = 'SELECT SUM(og.realprice) FROM ' . tablename('ewei_shop_order_goods') . ' og LEFT JOIN ' . tablename('ewei_shop_order') . ' o ON og.orderid = o.id  WHERE o.openid = :openid AND o.status >= 1 AND o.uniacid = :uniacid LIMIT 1';
                                    $moneycount = pdo_fetchcolumn($sql, array( ':uniacid' => $_W ['uniacid'], ':openid' => $openid ));
                                    $can = $moneycount >= floatval($set ['become_moneycount']);
                                } else {
                                    $can = false;
                                }

                                if ($can) {
                                    $become_check = intval($set ['become_check']); // 成为分销商是否需要审核。
                                    pdo_update('ewei_shop_member', array( 'status' => 1, 'isagent' => $become_check, 'agenttime' => $time ), array( 'uniacid' => $_W ['uniacid'], 'id' => $member ['id'] ));

                                    if ($become_check == 1) {
                                        $this->sendMessage($openid, array( 'nickname' => $member ['nickname'], 'agenttime' => $time ), TM_COMMISSION_BECOME);
                                    }
                                }
                            }
                        }

                        if (!empty( $member ['agentid'] )) {
                            $parent = m('member')->getMember($member ['agentid']);

                            if (empty( $parent ) || $parent ['isagent'] != 1 || $parent ['status'] != 1) {
                                return false;
                            }
                            if ($order ['agentid'] != $parent ['id']) {
                                return false;
                            }

                            $this->sendMessage($parent ['openid'], array( 'nickname' => $member ['nickname'], 'ordersn' => $order ['ordersn'], 'price' => $order ['goodsprice'], 'paytime' => $order ['paytime'] ), TM_COMMISSION_ORDER_PAY);
                        }

                        return true;
                    }
                }
            }

            return false;
        }

        /**
         * 订单完成检测
         * @param int $orderid
         * @return bool
         */
        public function checkOrderFinish($orderid = 0){
            global $_W;

            $set = $this->getSet();

            if (!empty( $orderid ) && !empty( $set['level'] )) {
                $this->_updateRecordOrderStatus($orderid, 'finish'); // 佣金状态变更

                $filed = array( 'id', 'openid', 'ordersn', 'goodsprice', 'agentid', 'finishtime' );
                $order = m('order')->getOrderInfo($orderid, $filed);

                $openid = $order['openid'];
                $member = m('member')->getMember($openid);
                if (empty( $member )) {
                    return false;
                }

                $time = time();
                $isagent = $member['isagent'] == 1 && $member['status'] == 1;

                if (empty( $isagent ) && $set['become_order'] == 1) {

                    if ($set['become'] == 2 || $set['become'] == 3) {
                        if (!empty( $member['agentid'] )) {
                            $parent = m('member')->getMember($member['agentid']);
                            if (empty( $parent ) || $parent['isagent'] != 1 || $parent['status'] != 1) {
                                return;
                            }
                        }

                        if ($set['become'] == '2') {
                            $sql = 'SELECT COUNT(id) FROM ' . tablename('ewei_shop_order') . ' WHERE openid = :openid AND status >= 3 AND uniacid = :uniacid LIMIT 1';
                            $ordercount = pdo_fetchcolumn($sql, array( ':uniacid' => $_W['uniacid'], ':openid' => $openid ));
                            $can = $ordercount >= intval($set['become_ordercount']);
                        } else if ($set['become'] == '3') {
                            $sql = 'SELECT SUM(goodsprice) FROM ' . tablename('ewei_shop_order') . ' WHERE openid = :openid AND status >= 3 AND uniacid = :uniacid LIMIT 1';
                            $moneycount = pdo_fetchcolumn($sql, array( ':uniacid' => $_W['uniacid'], ':openid' => $openid ));
                            $can = $moneycount >= floatval($set['become_moneycount']);
                        } else {
                            $can = false;
                        }

                        if ($can) {
                            $become_check = intval($set['become_check']);
                            pdo_update('ewei_shop_member', array( 'status' => 1, 'isagent' => $become_check, 'agenttime' => $time ), array( 'uniacid' => $_W['uniacid'], 'id' => $member['id'] ));

                            if ($become_check == 1) {
                                $this->sendMessage($member['openid'], array( 'nickname' => $member['nickname'], 'agenttime' => $time ), TM_COMMISSION_BECOME);
                            }
                        }
                    }

                } else {
                    $this->upgradeLevel($openid);
                }

                // 订单佣金通知
                if (!empty( $member['agentid'] )) {
                    $parent = m('member')->getMember($member['agentid']);

                    if (empty( $parent ) || $parent['isagent'] != 1 || $parent['status'] != 1) {
                        return false;
                    }
                    if ($order['agentid'] != $parent['id']) {
                        return false;
                    }

                    $this->sendMessage($parent['openid'], array( 'nickname' => $member['nickname'], 'ordersn' => $order['ordersn'], 'price' => $order['goodsprice'], 'finishtime' => $order['finishtime'] ), TM_COMMISSION_ORDER_FINISH);
                }

                return true;
            }

            return false;
        }


        /**
         * 订单退款，佣金删除。
         * @param $orderid
         * @return bool
         */
        public function checkOrderRefund($orderid){
            global $_W;

            if(!empty($orderid)){

                $status = pdo_update('ewei_shop_commission_record', array('c_status' => -2, 'c_content' => '订单退款，佣金取消。'), array('orderid' => $orderid, 'uniacid' => $_W['uniacid']));

                if($status !== false){
                    return true;
                }

            }

            return false;
        }

        /**
         * 订单取消退款，佣金返还。
         * @param $orderid
         * @return bool
         */
        public function checkOrderRefundCancel($orderid){
            global $_W;

            if(!empty($orderid)){

                $status = pdo_update('ewei_shop_commission_record', array('c_status' => 0, 'c_content' => ''), array('orderid' => $orderid, 'uniacid' => $_W['uniacid']));

                if($status !== false){
                    return true;
                }

            }

            return false;
        }

        /**
         * 获取指定用户的小店
         * @param $m
         * @return array|bool
         */
        public function getShop($m){
            global $_W;
            $member = m('member')->getMember($m);
            $shop = pdo_fetch('select * from ' . tablename('ewei_shop_commission_shop') . ' where uniacid=:uniacid and mid=:mid limit 1', array( ':uniacid' => $_W['uniacid'], ':mid' => $member['id'] ));
            $sysset = m('common')->getSysset(array( 'shop', 'share' ));
            $set = $sysset['shop'];
            $share = $sysset['share'];
            $desc = $share['desc'];
            if (empty( $desc )) {
                $desc = $set['description'];
            }
            if (empty( $desc )) {
                $desc = $set['name'];
            }
            if (empty( $shop )) {
                $shop = array( 'name' => $member['nickname'] . '的小店', 'logo' => $member['avatar'], 'desc' => $desc, 'img' => tomedia($set['img']) );
            } else {
                if (empty( $shop['name'] )) {
                    $shop['name'] = $member['nickname'] . '的小店';
                }
                if (empty( $shop['logo'] )) {
                    $shop['logo'] = tomedia($member['avatar']);
                }
                if (empty( $shop['img'] )) {
                    $shop['img'] = tomedia($set['img']);
                }
                if (empty( $shop['desc'] )) {
                    $shop['desc'] = $desc;
                }
            }
            return $shop;
        }

        /**
         * 获取所有分销商等级
         * @param bool $all
         * @return array
         */
        public function getLevels($all = true){
            global $_W;
            if ($all) {
                return pdo_fetchall('select * from ' . tablename('ewei_shop_commission_level') . ' where uniacid=:uniacid order by commission1 asc', array( ':uniacid' => $_W['uniacid'] ));
            } else {
                return pdo_fetchall('select * from ' . tablename('ewei_shop_commission_level') . ' where `uniacid` = :uniacid and `value` > 0 order by commission1 asc', array( ':uniacid' => $_W['uniacid'] ));
            }
        }

        /**
         * 获取指定用户的分销商等级
         * @param $openid
         * @return bool
         */
        public function getLevel($openid){
            global $_W;
            if (empty( $openid )) {
                return false;
            }
            $member = m('member')->getMember($openid);
            if (empty( $member['agentlevel'] )) {
                return false;
            }
            $level = pdo_fetch('select * from ' . tablename('ewei_shop_commission_level') . ' where uniacid=:uniacid and id=:id limit 1', array( ':uniacid' => $_W['uniacid'], ':id' => $member['agentlevel'] ));
            return $level;
        }

        /**
         * 对指定用户进行升级（内含条件检测）
         * @param $openid
         */
        public function upgradeLevel($openid){
            global $_W;
            if (empty( $openid )) {
                return;
            }
            $set = $this->getSet();
            if (empty( $set['level'] )) {
                return;
            }
            $m = m('member')->getMember($openid);
            $agents = array();
            if (!empty( $m )) {
                if($m['isagent'] == 1 && $m['status'] == 1){
                    $agents[] = $m;
                }

                if (!empty( $m['agentid'] )) {
                    $m1 = m('member')->getMember($m['agentid']);
                    if (!empty( $m1 )) {
                        $agents[] = $m1;
                        if (!empty( $m1['agentid'] ) && $m1['isagent'] == 1 && $m1['status'] == 1) {
                            $m2 = m('member')->getMember($m1['agentid']);
                            if (!empty( $m2 ) && $m2['isagent'] == 1 && $m2['status'] == 1) {
                                $agents[] = $m2;
                                if (!empty( $m2['agentid'] ) && $m2['isagent'] == 1 && $m2['status'] == 1) {
                                    $m3 = m('member')->getMember($m1['agentid']);
                                    if (!empty( $m3 ) && $m3['isagent'] == 1 && $m3['status'] == 1) {
                                        $agents[] = $m3;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            /**
             * 为支持多条件升级，方案如下：
             * 1. 修改基础设置，增加leveltype选项（自定义）
             * 2. 修改commission_level表，增加条件，权重，值，是否脱离上级。
             * 3. 增加model类中多重多升级判断升级方法。
             * 4. 可升级等级与当前等级权重判断，是否进行升级。
             */
            foreach ($agents as $agent) {
                if (!empty( $info['agentnotupgrade'] )) {
                    continue;
                }
                $levels = $this->checkLevel($agent['openid']);

                if(!empty($levels)){
                    $newlevel = $levels['newlevel'];
                    $oldlevel = $levels['nowLevel'];

                    // 增加了权重值判断，避免手动调整用户后，判断时降级。
                    if (!empty( $newlevel ) && $newlevel['id'] != $agent['agentlevel'] && $newlevel['priority'] > $oldlevel['priority']) {

                        if (empty( $oldlevel['id'] )) {
                            $oldlevel = array( 'levelname' => empty( $set['levelname'] ) ? '普通等级' : $set['levelname'], 'commission1' => $set['commission1'], 'commission2' => $set['commission2'], 'commission3' => $set['commission3'] );
                        }

                        if($newlevel['split'] == 0){
                            $data = array( 'agentlevel' => $newlevel['id'] );
                        }else{
                            if(!empty( $agent['agentid'] )){
                                $data = array( 'agentlevel' => $newlevel['id'], 'agentid' => 0, 'oldagentid' => $agent['agentid'], 'splittime' => time() );
                                plog('commission.level.edit', '会员升级时，脱离了上级。[本人ID:'. $agent['id'] .',原上级ID:'. $agent['agentid'].']');
                            }else{
                                $data = array( 'agentlevel' => $newlevel['id'] );
                            }
                        }

                        // 分销等级与会员等级同步。
                        if(!empty($set['levelsynchro'])){
                            $sql = 'SELECT `id` FROM '. tablename('ewei_shop_member_level').' WHERE `uniacid` = :uniacid AND `levelname` = :levelname ';
                            $pam = array(':uniacid' => $_W['uniacid'], ':levelname' => $newlevel['levelname']);
                            $memberLevelId = pdo_fetchcolumn($sql, $pam);

                            if(!empty($memberLevelId)){
                                $data['level'] = $memberLevelId;
                            }
                        }

                        pdo_update('ewei_shop_member', $data, array( 'id' => $agent['id'] ));

                        $this->sendMessage($agent['openid'], array( 'nickname' => $agent['nickname'], 'oldlevel' => $oldlevel, 'newlevel' => $newlevel ), TM_COMMISSION_UPGRADE);
                    }
                }

            }

        }

        /**
         * 用户是否升级的判断检测
         * @param $openid
         * @return array|bool
         */
        public function checkLevel($openid){
            global $_W;

            $set = $this->getSet();

            if(!empty($openid) && !empty($set['level'])){
                $member = m('member')->getMember($openid);

                if(empty($member)){
                    return false;
                }

                // 默认为自购订单总额(完成的订单)
                $set['leveltype'] = empty($set['leveltype']) ? 'ordersum' : $set['leveltype'];
                $levels = $this->getLevels(false);

                if(!empty($levels)){

                    $canLevel = array();
                    $nowLevel = array();

                    foreach ($levels as $level){

                        // 若不设置值，则该等级无法通过升级得到。
                        if(empty($level['value'])){
                            continue;
                        }

                        // 若用户等级与当前循环等级一致时，跳过查询。
                        if($level['id'] == $member['agentlevel']){
                            $nowLevel = $level;
                        }else{
                            // 若当前等级的升级条件依据为自定义时，则以当前等级的升级条件依据取值。
                            $types = !empty($level['leveltype']) ? $level['leveltype'] : $set['leveltype'];
                            $types = explode(':', $types);

                            foreach($types as $type){
                                $value = $this->_getLevelValue($member, $type, $level['value']);

                                if(!empty($level['value']) && intval($level['value']) > 0 && !empty($value) && $level['value'] <= $value){
                                    if(empty($canLevel)){
                                        // 当可升级信息为空时，则将当前等级赋予用户可升级备选。
                                        $canLevel = $level;
                                    }else{
                                        // 当可升级备选不为空时，则根据优先级（权重值），取可升级的最大值。
                                        $canLevel = $canLevel['priority'] < $level['priority'] ? $level : $canLevel;
                                    }
                                }
                            }

                        }

                    }

                    return array('newlevel' => $canLevel, 'nowLevel' => $nowLevel);
                }

            }

            return false;
        }

        /**
         * 获取对应升级依据的值
         * @param $member
         * @param $leveltype
         * @param $goodsid // 购买指定商品升级，仅在特殊类型中存在值。
         * @return int
         */
        private function _getLevelValue($member, $leveltype, $goodsid = 0){
            $openid = $member['openid'];
            $value = 0;

            // 自购订单总额(完成的订单) : ordersum
            if($leveltype == 'ordersum'){
                $result = m('order')->getOrderStatistics($openid, array('ordersum'));
                $value = $result['ordersum'];
            }

            // 自购订单总数(完成的订单) : ordercount
            if($leveltype == 'ordercount'){
                $result = m('order')->getOrderStatistics($openid, array('ordercount'));
                $value = $result['ordercount'];
            }

            // 分销订单总额(完成的订单) : agentordersum
            if($leveltype == 'agentordersum'){
                $result = m('order')->getOrderStatistics($openid, array('agentordersum'));
                $value = $result['agentordersum'];
            }

            // 分销订单总数(完成的订单) : agentordercount
            if($leveltype == 'agentordercount'){
                $result = m('order')->getOrderStatistics($openid, array('agentordercount'));
                $value = $result['agentordercount'];
            }

            // 一级分销订单总额(完成的订单) : agent1ordersum
            if($leveltype == 'agent1ordersum'){
                $result = m('order')->getOrderStatistics($openid, array('agent1ordersum'));
                $value = $result['agent1ordersum'];
            }

            // 一级分销订单总数(完成的订单) : agent1ordercount
            if($leveltype == 'agent1ordercount'){
                $result = m('order')->getOrderStatistics($openid, array('agent1ordercount'));
                $value = $result['agent1ordercount'];
            }

            // 刷新缓存。仅分销商。
            $noCacheTeamLists = array(
                'agentcount',
                'agent1count',
            );

            if(in_array($leveltype, $noCacheTeamLists)){
                $this->getCommissionTeam($member['id'], 1, 0, null, true);
            }

            // 刷新缓存。分销商及非分销商。
            $noCacheTeamAllLists = array(
                'agentallcount',
                'agent1allcount',
            );

            if(in_array($leveltype, $noCacheTeamAllLists)){
                $this->getCommissionTeamAll($member['id'], 1, 0, null, true);
            }

            // 下线总人数（分销商 + 非分销商） : agentallcount
            if($leveltype == 'agentallcount'){
                $result = $this->getCommissionTeamCount($member['id'], array(1,2,3), true);
                $value = $result['all'];
            }

            // 下线总人数（分销商） : agentcount
            if($leveltype == 'agentcount'){
                $result = $this->getCommissionTeamCount($member['id'], array(1,2,3));
                $value = $result['all'];
            }

            // 一级下线总人数（分销商 + 非分销商） : agent1allcount
            if($leveltype == 'agent1allcount'){
                $result = $this->getCommissionTeamCount($member['id'], array(1), true);
                $value = $result[1];
            }

            // 一级下线总人数（分销商）: agent1count
            if($leveltype == 'agent1count'){
                $result = $this->getCommissionTeamCount($member['id'], array(1));
                $value = $result[1];
            }

            return $value;
        }

        /**
         * 发送分销相关的信息
         * @param string $openid
         * @param array $data
         * @param string $message_type
         */
        public function sendMessage($openid = '', $data = array(), $message_type = ''){
            global $_W, $_GPC;
            $set = $this->getSet();
            $tm = $set['tm'];
            $templateid = $tm['templateid'];
            $member = m('member')->getMember($openid);
            $usernotice = unserialize($member['noticeset']);
            if (!is_array($usernotice)) {
                $usernotice = array();
            }
            if ($message_type == TM_COMMISSION_AGENT_NEW && !empty( $tm['commission_agent_new'] ) && empty( $usernotice['commission_agent_new'] )) {
                $message = $tm['commission_agent_new'];
                $message = str_replace('[昵称]', $data['nickname'], $message);
                $message = str_replace('[时间]', date('Y-m-d H:i:s', $data['childtime']), $message);
                $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_agent_newtitle'] ) ? $tm['commission_agent_newtitle'] : '新增下线通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                if (!empty( $templateid )) {
                    m('message')->sendTplNotice($openid, $templateid, $msg);
                } else {
                    m('message')->sendCustomNotice($openid, $msg);
                }
            } else {
                if ($message_type == TM_COMMISSION_ORDER_PAY && !empty( $tm['commission_order_pay'] ) && empty( $usernotice['commission_order_pay'] )) {
                    $message = $tm['commission_order_pay'];
                    $message = str_replace('[昵称]', $data['nickname'], $message);
                    $message = str_replace('[时间]', date('Y-m-d H:i:s', $data['paytime']), $message);
                    $message = str_replace('[订单编号]', $data['ordersn'], $message);
                    $message = str_replace('[订单金额]', $data['price'], $message);
                    $message .= '（注：推广订单显示可能存在一定延迟，请等待几分钟后查看。）';
                    $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_order_paytitle'] ) ? $tm['commission_order_paytitle'] : '下线付款通知' ), 'keyword2' => array( 'value' => $message ) );
                    if (!empty( $templateid )) {
                        m('message')->sendTplNotice($openid, $templateid, $msg);
                    } else {
                        m('message')->sendCustomNotice($openid, $msg);
                    }
                } else {
                    if ($message_type == TM_COMMISSION_ORDER_FINISH && !empty( $tm['commission_order_finish'] ) && empty( $usernotice['commission_order_finish'] )) {
                        $message = $tm['commission_order_finish'];
                        $message = str_replace('[昵称]', $data['nickname'], $message);
                        $message = str_replace('[时间]', date('Y-m-d H:i:s', $data['finishtime']), $message);
                        $message = str_replace('[订单编号]', $data['ordersn'], $message);
                        $message = str_replace('[订单金额]', $data['price'], $message);
                        $message .= '（注：推广订单显示可能存在一定延迟，请等待几分钟后查看。）';
                        $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_order_finishtitle'] ) ? $tm['commission_order_finishtitle'] : '下线确认收货通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                        if (!empty( $templateid )) {
                            m('message')->sendTplNotice($openid, $templateid, $msg);
                        } else {
                            m('message')->sendCustomNotice($openid, $msg);
                        }
                    } else {
                        if ($message_type == TM_COMMISSION_APPLY && !empty( $tm['commission_apply'] ) && empty( $usernotice['commission_apply'] )) {
                            $message = $tm['commission_apply'];
                            $message = str_replace('[昵称]', $member['nickname'], $message);
                            $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                            $message = str_replace('[金额]', $data['commission'], $message);
                            $message = str_replace('[提现方式]', $data['type'], $message);
                            $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_applytitle'] ) ? $tm['commission_applytitle'] : '提现申请提交成功', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                            if (!empty( $templateid )) {
                                m('message')->sendTplNotice($openid, $templateid, $msg);
                            } else {
                                m('message')->sendCustomNotice($openid, $msg);
                            }
                        } else {
                            if ($message_type == TM_COMMISSION_CHECK && !empty( $tm['commission_check'] ) && empty( $usernotice['commission_check'] )) {
                                $message = $tm['commission_check'];
                                $message = str_replace('[昵称]', $member['nickname'], $message);
                                $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                                $message = str_replace('[金额]', $data['commission'], $message);
                                $message = str_replace('[提现方式]', $data['type'], $message);
                                $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_checktitle'] ) ? $tm['commission_checktitle'] : '提现申请审核处理完成', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                if (!empty( $templateid )) {
                                    m('message')->sendTplNotice($openid, $templateid, $msg);
                                } else {
                                    m('message')->sendCustomNotice($openid, $msg);
                                }
                            } else {
                                if ($message_type == TM_COMMISSION_PAY && !empty( $tm['commission_pay'] ) && empty( $usernotice['commission_pay'] )) {
                                    $message = $tm['commission_pay'];
                                    $message = str_replace('[昵称]', $member['nickname'], $message);
                                    $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                                    $message = str_replace('[金额]', $data['commission'], $message);
                                    $message = str_replace('[提现方式]', $data['type'], $message);
                                    $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_paytitle'] ) ? $tm['commission_paytitle'] : '佣金打款通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                    if (!empty( $templateid )) {
                                        m('message')->sendTplNotice($openid, $templateid, $msg);
                                    } else {
                                        m('message')->sendCustomNotice($openid, $msg);
                                    }
                                } else {
                                    if ($message_type == TM_COMMISSION_UPGRADE && !empty( $tm['commission_upgrade'] ) && empty( $usernotice['commission_upgrade'] )) {
                                        $message = $tm['commission_upgrade'];
                                        $message = str_replace('[昵称]', $member['nickname'], $message);
                                        $message = str_replace('[时间]', date('Y-m-d H:i:s', time()), $message);
                                        $message = str_replace('[旧等级]', $data['oldlevel']['levelname'], $message);
                                        $message = str_replace('[旧一级分销比例]', $data['oldlevel']['commission1'] . '%', $message);
                                        $message = str_replace('[旧二级分销比例]', $data['oldlevel']['commission2'] . '%', $message);
                                        $message = str_replace('[旧三级分销比例]', $data['oldlevel']['commission3'] . '%', $message);
                                        $message = str_replace('[新等级]', $data['newlevel']['levelname'], $message);
                                        $message = str_replace('[新一级分销比例]', $data['newlevel']['commission1'] . '%', $message);
                                        $message = str_replace('[新二级分销比例]', $data['newlevel']['commission2'] . '%', $message);
                                        $message = str_replace('[新三级分销比例]', $data['newlevel']['commission3'] . '%', $message);
                                        $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_upgradetitle'] ) ? $tm['commission_upgradetitle'] : '分销等级升级通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                        if (!empty( $templateid )) {
                                            m('message')->sendTplNotice($openid, $templateid, $msg);
                                        } else {
                                            m('message')->sendCustomNotice($openid, $msg);
                                        }
                                    } else {
                                        if ($message_type == TM_COMMISSION_BECOME && !empty( $tm['commission_become'] ) && empty( $usernotice['commission_become'] )) {
                                            $message = $tm['commission_become'];
                                            $message = str_replace('[昵称]', $data['nickname'], $message);
                                            $message = str_replace('[时间]', date('Y-m-d H:i:s', $data['agenttime']), $message);
                                            $msg = array( 'keyword1' => array( 'value' => !empty( $tm['commission_becometitle'] ) ? $tm['commission_becometitle'] : '成为分销商通知', "color" => "#73a68d" ), 'keyword2' => array( 'value' => $message, "color" => "#73a68d" ) );
                                            if (!empty( $templateid )) {
                                                m('message')->sendTplNotice($openid, $templateid, $msg);
                                            } else {
                                                m('message')->sendCustomNotice($openid, $msg);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        /**
         * 分权信息
         * @return array
         */
        public function perms(){
            return array(
                'commission' => array(
                    'text' => $this->getName(),
                    'isplugin' => true,
                    'child' => array(
                        'cover' => array( 'text' => '入口设置' ),
                        'agent' => array( 'text' => '分销商', 'view' => '浏览', 'check' => '审核-log', 'edit' => '修改-log', 'delete' => '删除-log', 'user' => '查看下线', 'order' => '查看推广订单(还需有订单权限)', 'change' => '变更上级-log' ),
                        'level' => array( 'text' => '分销商等级', 'view' => '浏览', 'add' => '添加-log', 'edit' => '修改-log', 'delete' => '删除-log' ),
                        'apply' => array( 'text' => '佣金审核', 'view1' => '浏览待审核', 'view2' => '浏览已审核', 'view3' => '浏览已打款', 'view_1' => '浏览无效', 'check' => '审核-log', 'pay' => '打款-log', 'cancel' => '重新审核-log' ),
                        'notice' => array( 'text' => '通知设置-log' ),
                        'set' => array( 'text' => '基础设置-log' )
                    )
                )
            );
        }
    }
}